package com.task.util;

import com.task.exception.CommonException;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/*
 *
 * @description httpClient 工具类
 * @author carey
 * @date 2018/2/6 上午12:46
 * @version 1.0
 */

public class HttpRequestUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpRequestUtils.class);    //日志记录

    private Map<String,Object> headMap;

    public HttpRequestUtils(Map<String,Object> headMap){
         this.headMap=headMap;

    }

    public  Map<String,Object> getHeadMap(){
        return headMap;
    }

    /**
     * post请求
     * @param url         url地址
     * @param param     参数
     * @return
     */
    public  String httpClient(String url, Map<String,Object> param, HttpType httpType) {
        //post请求返回结果
        CloseableHttpClient httpClient = HttpClients.createDefault();
        String str = "";
        HttpResponse result = null;

        Set<String> stringSet= param.keySet();
        logger.info("-------------------------------------------");
        for(String key:stringSet){

            logger.info("请求字段："+key+"  value: " + param.get(key));
        }

        logger.info("-------------------------------------------");
        try {
            url = URLDecoder.decode(url, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Set<String> keyMap = getHeadMap().keySet();

        try {


            //拼接参数
            List<NameValuePair> nvps = new ArrayList<>();
            Set<String> keyMaps = param.keySet();
            for (String key : keyMaps) {
                nvps.add(new BasicNameValuePair(key, param.get(key).toString()));
            }

        switch (httpType) {
            case POST:
                HttpPost httpPost = new HttpPost(url);
                for (String key : keyMap) {
                    httpPost.setHeader(key,getHeadMap().get(key).toString());
                }
                httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
                result= httpClient.execute(httpPost);
                break;

            case GET:
                //拼接参数
                url= setVal(url,getNameValuePairList(param));
                HttpGet httpGet=new HttpGet(url);
                for (String key : keyMap) {
                    httpGet.setHeader(key,getHeadMap().get(key).toString());
                }

                result= httpClient.execute(httpGet);
                break;
            case PUT:
                HttpPut httpPut=new HttpPut(url);
                for (String key : keyMap) {
                    httpPut.setHeader(key,getHeadMap().get(key).toString());
                }
                httpPut.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
                result= httpClient.execute(httpPut);
                break;
            case DELETE:
                url= setVal(url,getNameValuePairList(param));
                HttpDelete httpDelete=new HttpDelete(url);
                for (String key : keyMap) {
                    httpDelete.setHeader(key,getHeadMap().get(key).toString());
                }
                result= httpClient.execute(httpDelete);
                break;

        }

        } catch (IOException e) {
            e.printStackTrace();
        }
                /**请求发送成功，并得到响应**/
                if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                    try {
                        /**读取服务器返回过来的json字符串数据**/
                        str = EntityUtils.toString(result.getEntity());
                        /**把json字符串转换成json对象**/

                    } catch (Exception e) {
                        logger.error("post请求提交失败:" + url, e);
                    }
                }
                return str;
        }


    /**
     * @Description 组装带参数的URL
     * @param url
     * @param params
     * @return
     */
        public String  setVal(String url,List<NameValuePair> params){

            if (params != null) {
                String param = StringUtils.join(params, "&");
                if (url.contains("?")) {
                    url = url + "&" + param;
                } else {
                    url = url + "?" + param;
                }
            }
            return  url;


        }


        public List<NameValuePair> getNameValuePairList(Map<String,Object> param){
            List<NameValuePair> nameValuePairs = new ArrayList<>();
            Set<String> getKeyMap = param.keySet();
                for (String key : getKeyMap) {
                    nameValuePairs.add(new BasicNameValuePair(key, param.get(key).toString()));
            }
            return nameValuePairs;
        }
        
        /**
         *  
         * @author carey
         * @see  
         * @date 2018/2/13 上午1:26
         * @param [jsonStr, response]
         * @return void
         * @exception 
         */
        public static void responseJSON(Object jsonStr,
                                        HttpServletResponse response) throws IOException, CommonException {
            if(null==jsonStr){
                 throw new CommonException("jsonStr is null !");
            }
            //指定返回的格式为JSON格式
            response.setContentType("application/json;charset=utf-8");
            PrintWriter printWriter = response.getWriter();
            printWriter.write(jsonStr.toString());
        }


}